package com.yljk.imdoctor.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMCursorResult;
import com.hyphenate.chat.EMCustomMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.exceptions.HyphenateException;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.yilijk.base.network.RequestParams;
import com.yilijk.base.network.config.BaseConfig;
import com.yilijk.base.network.https.HttpCallBack;
import com.yilijk.base.network.https.HttpUtils;
import com.yilijk.base.network.https.interceptor.NetWorkUtils;
import com.yilijk.base.utils.ALog;
import com.yilijk.base.utils.ClickUtils;
import com.yilijk.base.utils.DevicesUtils;
import com.yilijk.base.utils.LoadingUtils;
import com.yljk.imdoctor.R;
import com.yljk.imdoctor.adapter.ConversationAdapter;
import com.yljk.imdoctor.adapter.OldConversationAdapter;
import com.yljk.imdoctor.entity.ConversationBean;
import com.yljk.imdoctor.entity.OldConversationBean;
import com.yljk.imdoctor.entity.ReadCountEntity;
import com.yljk.servicemanager.constants.ClickApi;
import com.yljk.servicemanager.constants.ConfigApi;
import com.yljk.servicemanager.constants.ReactApi;
import com.yljk.servicemanager.constants.RouterApi;
import com.yljk.servicemanager.constants.UrlApi;
import com.yljk.servicemanager.oldbase.ModuleBaseFragment;
import com.yljk.servicemanager.interfaceapi.IMBackApi;
import com.yljk.servicemanager.interfaceapi.NetWorkCallBack;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;

import okhttp3.ResponseBody;
import retrofit2.Call;

@Route(path = RouterApi.IMFRAGMENT)
public class ConversationListFragment extends ModuleBaseFragment {
    private TextView bottomInfo;
    //conversationlistview :Recycler
    private RecyclerView conversationRecycler;
    //conversationrefreshview :SmartRefreshLayout
    private SmartRefreshLayout conversationSmartRefresh;
    //loading:customDialog
    private LinearLayout systemMessage;
    private TextView itemMessagetitle;
    private TextView itemMessagedata;
    private TextView systemitemMessageinfo;
    private TextView unreadcount;
    private LinearLayout usesStatus;
    private boolean isFirstLoading = true;
    //系统消息回调
    private Call<ResponseBody> systemMessagePost;
    private Call<ResponseBody> conversationListGet;

    //=========================群组============================
    private ArrayList<ConversationBean.DataBean> doctorImMsgList;
    private ConversationAdapter conversationAdapter;
    //=========================关闭群组============================
    private ArrayList<OldConversationBean.DataBean.DoctorImMsgListBean> oldDoctorImMsgList;
    private OldConversationAdapter oldConversationAdapter;



    //static 代码段可以防止内存泄露
    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.white, android.R.color.black);//全局设置主题颜色
                return new ClassicsHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });

    }

    //handler
    private Handler handler = new Handler();
    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String stringExtra = intent.getStringExtra(ConfigApi.receiverUser);
            if (intent.getBooleanExtra(ConfigApi.receiverMsg, false)) {
                refreshMsg(stringExtra,false);
            }
            if (intent.getBooleanExtra(ConfigApi.receiverCMDMsg, false)) {
                refreshMsg(stringExtra,true);
            }
            if (intent.getBooleanExtra(ConfigApi.refreshRecall, false)) {
                EMMessage txtSendMessage = EMMessage.createTxtSendMessage("[对方撤回了一条消息]", stringExtra);
                emMessageJson(txtSendMessage);
            }
        }
    };

    //调用未读消息接口
    void getSystemMessage() {
        HttpUtils.post(UrlApi.notReadCount, new HttpCallBack<ReadCountEntity>() {
            @Override
            public void onSuccess(ReadCountEntity readCountEntity, int code) {
                if (readCountEntity.getCode() == 200 && readCountEntity.getData() != null) {
                    ReadCountEntity.DataBean data = readCountEntity.getData();
                    if (data.getCount() > 0) {
                        unreadcount.setVisibility(View.VISIBLE);
                    } else {
                        unreadcount.setVisibility(View.GONE);
                    }
                    if (data.getMessage() != null) {
                        ReadCountEntity.DataBean.MessageBean message = data.getMessage();
                        if (!TextUtils.isEmpty(message.getContent())) {
                            systemitemMessageinfo.setText(message.getContent());
                        } else {
                            systemitemMessageinfo.setText("暂无消息");
                        }
                        if (!TextUtils.isEmpty(message.getCreateTime())) {
                            itemMessagedata.setVisibility(View.VISIBLE);
                            itemMessagedata.setText(message.getCreateTime());
                        } else {
                            itemMessagedata.setVisibility(View.GONE);
                        }
                    }
                }
            }

            @Override
            public void onFailure(String failureMsg, int statusCode) {

            }
        });

    }


    @Override
    public int bondLayout() {
        return R.layout.fragment_conversation_list;
    }

    @Override
    public void initView() {
        usesStatus = (LinearLayout) findViewById(R.id.usesStatus);
        //注册广播
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BaseConfig.Receiver.BroadcastReceiver);
        getContext().registerReceiver(broadcastReceiver, intentFilter);
        //conversationrefreshview :SmartRefreshLayout
        conversationSmartRefresh = (SmartRefreshLayout) findViewById(R.id.conversationSmartRefresh);
        conversationSmartRefresh.setEnableLoadMore(hasNextPage);

        itemMessagedata = (TextView) findViewById(R.id.item_messagedata);
        systemitemMessageinfo = (TextView) findViewById(R.id.systemitem_messageinfo);
        unreadcount = (TextView) findViewById(R.id.unreadcount);

        bottomInfo = (TextView) findViewById(R.id.bottomInfo);
        systemMessage = (LinearLayout) findViewById(R.id.system_message);

        //customDialog
//        loadingDialog = new CustomeDialog.Builder(getContext()).create();
        //conversationlistview :Recycler
        conversationRecycler = (RecyclerView) findViewById(R.id.conversationList);

        conversationRecycler.setLayoutManager(new LinearLayoutManager(getContext()));
        if (ConfigApi.Open.isOpenGroup){
            doctorImMsgList = new ArrayList<>();
            conversationAdapter = new ConversationAdapter(doctorImMsgList);
            conversationRecycler.setAdapter(conversationAdapter);
            conversationAdapter.notifyDataSetChanged();
        }else{
            oldDoctorImMsgList = new ArrayList<>();
            oldConversationAdapter = new OldConversationAdapter(oldDoctorImMsgList);
            conversationRecycler.setAdapter(oldConversationAdapter);
            oldConversationAdapter.notifyDataSetChanged();
        }


    }


    @Override
    public void initData() {
        //获取状态栏高度
    }

    @Override
    public void initEvent() {
        conversationSmartRefresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (hasNextPage) {
                    pageIndex++;
                    getConversationList();
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageIndex = 1;
                pageSize = 1000;
                getConversationList();
            }
        });

        /**
         * 系统消息点击
         */
        ClickUtils.setFastOnClickListener(systemMessage, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ClickUtils.sendEvent(ClickApi.Msg.Msg_SysMsg,getActivity(),"系统消息点击");
                IMBackApi imOnClickApi = (IMBackApi) ARouter.getInstance().build(RouterApi.IMONCLICKIMPL).navigation();
                imOnClickApi.push(getContext(),
                        ReactApi.MY_DOCTORBUNDLE,
                        ReactApi.Mine.MessageContent);
            }
        });
        ClickUtils.setAdapterItemFastOnClickListener(conversationAdapter, new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ClickUtils.sendEvent(ClickApi.Msg.Msg_MsgList,getActivity(),"消息列表点击");
                IMBackApi imOnClickApi = (IMBackApi) ARouter.getInstance().build(RouterApi.IMONCLICKIMPL).navigation();
                Bundle bundle = new Bundle();
                try {
                    if (String.valueOf(String.valueOf(doctorImMsgList.get(position).getPatientId()))!=null
                            && String.valueOf(doctorImMsgList.get(position).getChargesListId())!=null
                            &&  String.valueOf(doctorImMsgList.get(position).getChargesListStatus())!=null
                            &&  String.valueOf(doctorImMsgList.get(position).getPatientImAccount())!=null
                            &&  String.valueOf(doctorImMsgList.get(position).getInquiringPatientId())!=null){
                        bundle.putString("uid", String.valueOf(doctorImMsgList.get(position).getPatientId()));
                        bundle.putString("patientId", String.valueOf(doctorImMsgList.get(position).getPatientId()));

                        bundle.putString("chargesListStatus", String.valueOf(doctorImMsgList.get(position).getChargesListStatus()));
                        bundle.putString("patientImAccount", String.valueOf(doctorImMsgList.get(position).getPatientImAccount()));
                        bundle.putString("inquiringPatientId", String.valueOf(doctorImMsgList.get(position).getInquiringPatientId()));
                        bundle.putString("chargesListId", String.valueOf(doctorImMsgList.get(position).getChargesListId()));
                        if (!TextUtils.isEmpty(doctorImMsgList.get(position).getImTeamId())){
                            imOnClickApi.push(getContext(),
                                    ReactApi.IM_DOCTORBUNDLE,
                                    ReactApi.Message.ETPImChating, bundle);
                        }else{
                            imOnClickApi.push(getContext(),
                                    ReactApi.IM_DOCTORBUNDLE,
                                    ReactApi.Message.ImChating, bundle);
                        }
                        openImChargeByChargeListId(doctorImMsgList.get(position).getChargesListId(),position);
                    }


//                if (doctorImMsgList.get(position).getImRecordHbaseDTO()!=null
//                        && doctorImMsgList.get(position).getImRecordHbaseDTO().getMsgType() == 100
//                        && ( doctorImMsgList.get(position).getImRecordHbaseDTO().getCustomEvent().equals("finish")||
//                        doctorImMsgList.get(position).getImRecordHbaseDTO().getCustomEvent().equals("to_evaluate")||
//                        doctorImMsgList.get(position).getImRecordHbaseDTO().getCustomEvent().equals("patient_evaluate_finish")||
//                        doctorImMsgList.get(position).getImRecordHbaseDTO().getCustomEvent().equals("refund")||
//                        doctorImMsgList.get(position).getImRecordHbaseDTO().getCustomEvent().equals("cancel")||
//                        doctorImMsgList.get(position).getImRecordHbaseDTO().getCustomEvent().equals("doctor_evaluate_thanks"))){
//                    imOnClickApi.OnClickMessageList(getContext(),
//                            ReactApi.IM_DOCTORBUNDLE,
//                            ReactApi.ImHistory, bundle);
//                }else{
//                }
//                if (doctorImMsgList.get(position).getPatientImAccount()!=null){
//                    EMConversation conversation = EMClient.getInstance().chatManager().getConversation(doctorImMsgList.get(position).getPatientImAccount());
//                    //指定会话消息未读数清零
//                    if (conversation != null) {
//                        conversation.markAllMessagesAsRead();
//                    }
//                    //消息已读回执
//                    try {
//                        EMClient.getInstance().chatManager().ackConversationRead(doctorImMsgList.get(position).getPatientImAccount());
//                    } catch (HyphenateException e) {
//                        e.printStackTrace();
//                    }
//                }
                }catch (Exception e){

                }
            }
        });

        ClickUtils.setAdapterItemFastOnClickListener(oldConversationAdapter, new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ClickUtils.sendEvent(ClickApi.Msg.Msg_MsgList,getActivity(),"消息列表点击");
                IMBackApi imOnClickApi = (IMBackApi) ARouter.getInstance().build(RouterApi.IMONCLICKIMPL).navigation();
                Bundle bundle = new Bundle();
                try {
                    if (String.valueOf(String.valueOf(oldDoctorImMsgList.get(position).getPatientId()))!=null
                            && String.valueOf(oldDoctorImMsgList.get(position).getChargesListId())!=null
                            &&  String.valueOf(oldDoctorImMsgList.get(position).getChargesListStatus())!=null
                            &&  String.valueOf(oldDoctorImMsgList.get(position).getPatientImAccount())!=null
                            &&  String.valueOf(oldDoctorImMsgList.get(position).getInquiringPatientId())!=null){
                        bundle.putString("uid", String.valueOf(oldDoctorImMsgList.get(position).getPatientId()));
                        bundle.putString("patientId", String.valueOf(oldDoctorImMsgList.get(position).getPatientId()));
                        bundle.putString("chargesListId", String.valueOf(oldDoctorImMsgList.get(position).getChargesListId()));
                        bundle.putString("chargesListStatus", String.valueOf(oldDoctorImMsgList.get(position).getChargesListStatus()));
                        bundle.putString("patientImAccount", String.valueOf(oldDoctorImMsgList.get(position).getPatientImAccount()));
                        bundle.putString("inquiringPatientId", String.valueOf(oldDoctorImMsgList.get(position).getInquiringPatientId()));
                        imOnClickApi.push(getContext(),
                                ReactApi.IM_DOCTORBUNDLE,
                                ReactApi.Message.ImChating, bundle);
                    }


//                if (doctorImMsgList.get(position).getImRecordHbaseDTO()!=null
//                        && doctorImMsgList.get(position).getImRecordHbaseDTO().getMsgType() == 100
//                        && ( doctorImMsgList.get(position).getImRecordHbaseDTO().getCustomEvent().equals("finish")||
//                        doctorImMsgList.get(position).getImRecordHbaseDTO().getCustomEvent().equals("to_evaluate")||
//                        doctorImMsgList.get(position).getImRecordHbaseDTO().getCustomEvent().equals("patient_evaluate_finish")||
//                        doctorImMsgList.get(position).getImRecordHbaseDTO().getCustomEvent().equals("refund")||
//                        doctorImMsgList.get(position).getImRecordHbaseDTO().getCustomEvent().equals("cancel")||
//                        doctorImMsgList.get(position).getImRecordHbaseDTO().getCustomEvent().equals("doctor_evaluate_thanks"))){
//                    imOnClickApi.OnClickMessageList(getContext(),
//                            ReactApi.IM_DOCTORBUNDLE,
//                            ReactApi.ImHistory, bundle);
//                }else{
//                }
                    if (oldDoctorImMsgList.get(position).getPatientImAccount()!=null){
                        EMConversation conversation = EMClient.getInstance().chatManager().getConversation(oldDoctorImMsgList.get(position).getPatientImAccount());
                        //指定会话消息未读数清零
                        if (conversation != null) {
                            conversation.markAllMessagesAsRead();
                        }
                        //消息已读回执
                        try {
                            EMClient.getInstance().chatManager().ackConversationRead(oldDoctorImMsgList.get(position).getPatientImAccount());
                        } catch (HyphenateException e) {
                            e.printStackTrace();
                        }
                        oldDoctorImMsgList.get(position).setUnReadCount(0);
                    }
                }catch (Exception e){

                }
                refreshConversationList();
            }
        });

    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        ClickUtils.sendEvent(ClickApi.Msg.Msg_Load,getActivity(),"消息列表载入");
        if (isFirstLoading){
            isFirstLoading = false;
            LoadingUtils.getLoadingUtils(getContext()).showLoading();
        }
        if (systemMessagePost!=null && systemMessagePost.isExecuted()){{
            systemMessagePost.cancel();
        }}
        getSystemMessage();
        if (conversationListGet!=null && conversationListGet.isExecuted()){
            conversationListGet.cancel();
        }

        getConversationList();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getContext().unregisterReceiver(broadcastReceiver);
    }

    /**
     * 获取消息列表
     */

    int pageIndex = 1;
    int pageSize = 1000;
    boolean hasNextPage = true;

    private void getConversationList() {
        if (ConfigApi.Open.isOpenGroup){
            getNewConversationList();
        }else{
            getOldConversationList();
        }
    }

    private void getOldConversationList() {
        RequestParams params = new RequestParams();
        params.put("pageIndex", pageIndex);
        params.put("pageSize", pageSize);
        HttpUtils.get(UrlApi.queryDoctorMsgList, params, new HttpCallBack<OldConversationBean>() {
            @Override
            public void onSuccess(OldConversationBean conversationBean, int code) {
                if (conversationBean.isResult()) {
                    hasNextPage = conversationBean.getData().isHasNextPage();
                    if (conversationBean.getData().getDoctorImMsgList() != null) {
                        if (oldDoctorImMsgList.size() == 0) {
                            for (int i = 0; i < conversationBean.getData().getDoctorImMsgList().size(); i++) {
                                OldConversationBean.DataBean.DoctorImMsgListBean doctorImMsgListBean = conversationBean.getData().getDoctorImMsgList().get(i);
                                EMConversation conversation = EMClient.getInstance().chatManager().getConversation(doctorImMsgListBean.getPatientImAccount());
                                if (conversation != null) {
                                    int unreadMsgCount = conversation.getUnreadMsgCount();
                                    doctorImMsgListBean.setUnReadCount(unreadMsgCount);
                                } else {
                                    doctorImMsgListBean.setUnReadCount(0);
                                }
                            }
                            oldDoctorImMsgList.clear();
                            oldDoctorImMsgList.addAll(conversationBean.getData().getDoctorImMsgList());
                        } else {
                            for (int i = 0; i < conversationBean.getData().getDoctorImMsgList().size(); i++) {
                                boolean flag = false;
                                int currentPosition = -1;
                                for (int j = 0; j < oldDoctorImMsgList.size(); j++) {
                                    if (conversationBean.getData().getDoctorImMsgList().get(i).getPatientImAccount().equals(oldDoctorImMsgList.get(j).getPatientImAccount())) {
                                        flag = true;
                                        currentPosition = j;
                                        continue;
                                    }
                                }
                                OldConversationBean.DataBean.DoctorImMsgListBean doctorImMsgListBean = conversationBean.getData().getDoctorImMsgList().get(i);
                                EMConversation conversation = EMClient.getInstance().chatManager().getConversation(doctorImMsgListBean.getPatientImAccount());
                                if (conversation != null) {
                                    int unreadMsgCount = conversation.getUnreadMsgCount();
                                    doctorImMsgListBean.setUnReadCount(unreadMsgCount);
                                } else {
                                    doctorImMsgListBean.setUnReadCount(0);
                                }
                                if (flag) {
                                    oldDoctorImMsgList.remove(currentPosition);
                                    oldDoctorImMsgList.add(doctorImMsgListBean);
                                } else {
                                    oldDoctorImMsgList.add(doctorImMsgListBean);
                                }
                            }
                        }

//                            doctorImMsgList.addAll(conversationBean.getData().getDoctorImMsgList());
                        refreshConversationList();
                    }
                } else {
                    Toast.makeText(getContext(), "" + conversationBean.getMsg(), Toast.LENGTH_SHORT).show();
                }
                LoadingUtils.getLoadingUtils(getContext()).dismissLoading();
            }

            @Override
            public void onFailure(String failureMsg, int statusCode) {
                LoadingUtils.getLoadingUtils(getContext()).dismissLoading();
            }
        });

    }

    private void getNewConversationList() {
        RequestParams params = new RequestParams();
        params.put("pageIndex", pageIndex);
        params.put("pageSize", pageSize);
        HttpUtils.get(UrlApi.queryDoctorMsgListNew, params, new HttpCallBack<ConversationBean>() {
            @Override
            public void onSuccess(ConversationBean conversationBean, int code) {
                if (conversationBean.isResult() && conversationBean.getData() != null) {

//                    if (doctorImMsgList.size() == 0) {
//                        doctorImMsgList.clear();
//                        doctorImMsgList.addAll(conversationBean.getData());
//                    } else {
//                        for (int i = 0; i < conversationBean.getData().size(); i++) {
//                            boolean flag = false;
//                            int currentPosition = -1;
//                            for (int j = 0; j < doctorImMsgList.size(); j++) {
//                                if (conversationBean.getData().get(i).getPatientImAccount().equals(doctorImMsgList.get(j).getPatientImAccount())) {
//                                    flag = true;
//                                    currentPosition = j;
//                                    continue;
//                                }
//                            }
//                            ConversationBean.DataBean doctorImMsgListBean = conversationBean.getData().get(i);
//                            if (flag) {
//                                doctorImMsgList.remove(currentPosition);
//                                doctorImMsgList.add(doctorImMsgListBean);
//                            } else {
//                                doctorImMsgList.add(doctorImMsgListBean);
//                            }
//                        }
//                    }
                    doctorImMsgList.clear();
                    doctorImMsgList.addAll(conversationBean.getData());
                    refreshConversationList();
                } else {
                    Toast.makeText(getContext(), "" + conversationBean.getMsg(), Toast.LENGTH_SHORT).show();
                }
                LoadingUtils.getLoadingUtils(getContext()).dismissLoading();
            }

            @Override
            public void onFailure(String failureMsg, int statusCode) {
                LoadingUtils.getLoadingUtils(getContext()).dismissLoading();
            }
        });
    }

    /**
     * 消息列表刷新
     */
    void refreshConversationList() {
       if (ConfigApi.Open.isOpenGroup){
           refreshNewList();
       }else{
           refreshOldList();
       }
    }

    private void refreshOldList() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                Collections.sort(oldDoctorImMsgList);
                oldConversationAdapter.notifyDataSetChanged();
                conversationSmartRefresh.setEnableLoadMore(hasNextPage);
                if (hasNextPage) {
                    bottomInfo.setVisibility(View.GONE);
                } else {
                    if (oldDoctorImMsgList.size() >= 10) {
                        bottomInfo.setVisibility(View.VISIBLE);
                    } else {
                        bottomInfo.setVisibility(View.GONE);
                    }
                }
                conversationSmartRefresh.finishRefresh();
                conversationSmartRefresh.finishLoadMore();
                LoadingUtils.getLoadingUtils(getContext()).dismissLoading();
            }
        });

    }

    private void refreshNewList() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                conversationAdapter.notifyDataSetChanged();
                conversationSmartRefresh.setEnableLoadMore(hasNextPage);
                if (hasNextPage) {
                    bottomInfo.setVisibility(View.GONE);
                } else {
                    if (doctorImMsgList.size() >= 10) {
                        bottomInfo.setVisibility(View.VISIBLE);
                    } else {
                        bottomInfo.setVisibility(View.GONE);
                    }
                }
                conversationSmartRefresh.finishRefresh();
                conversationSmartRefresh.finishLoadMore();
                LoadingUtils.getLoadingUtils(getContext()).dismissLoading();
            }
        });
    }

    /**
     * 解析消息
     */
    //回调消息判断逻辑
    public void emMessageJson(EMMessage emmessage) {
        EMMessage.Type type = emmessage.getType();
        String content = "";
        int msgType = 0;
        String event = "";
        if (type == EMMessage.Type.TXT) {
            EMTextMessageBody body = (EMTextMessageBody) emmessage.getBody();
            if (body != null && body.getMessage() != null) {
                content = body.getMessage();
                msgType = 0;
            }
        } else if (type == EMMessage.Type.IMAGE) {
            content = "[图片消息]";
            msgType = 1;
        } else if (type == EMMessage.Type.VOICE) {
            content = "[语音消息]";
            msgType = 2;
        } else if (type == EMMessage.Type.VIDEO) {
            content = "[视频消息]";
            msgType = 3;
        } else if (type == EMMessage.Type.FILE) {
            content = "[文件消息]";
            msgType = 6;
        } else if (type == EMMessage.Type.CUSTOM) {
            msgType = 7;
            EMCustomMessageBody body = (EMCustomMessageBody) emmessage.getBody();
            if (body != null) {
                event = body.event();
            }
        } else if (type == EMMessage.Type.CMD) {
//            doctorImMsgList.clear();
            getConversationList();
        }
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(emmessage.getMsgTime());
        if (ConfigApi.Open.isOpenGroup){
            for (int i = 0; i < doctorImMsgList.size(); i++) {
                if (doctorImMsgList.get(i).getPatientImAccount()!=null && doctorImMsgList.get(i).getPatientImAccount().equals(emmessage.getFrom())) {
                    if (doctorImMsgList.get(i).getImRecordHbaseDTO() != null) {
                        doctorImMsgList.get(i).getImRecordHbaseDTO().setMsgType(msgType);
                        doctorImMsgList.get(i).getImRecordHbaseDTO().setContent(content);
                        doctorImMsgList.get(i).getImRecordHbaseDTO().setCustomEvent(event);
                        doctorImMsgList.get(i).setUpdateTime(format);
                    } else {
                        ConversationBean.DataBean.ImRecordHbaseDTOBean imRecordHbaseDTOBean = new ConversationBean.DataBean.ImRecordHbaseDTOBean();
                        imRecordHbaseDTOBean.setMsgType(msgType);
                        imRecordHbaseDTOBean.setContent(content);
                        imRecordHbaseDTOBean.setCustomEvent(event);
                        doctorImMsgList.get(i).setImRecordHbaseDTO(imRecordHbaseDTOBean);
                    }
                }
            }
        }else{
            for (int i = 0; i < oldDoctorImMsgList.size(); i++) {
                if (oldDoctorImMsgList.get(i).getPatientImAccount()!=null && oldDoctorImMsgList.get(i).getPatientImAccount().equals(emmessage.getFrom())) {
                    OldConversationBean.DataBean.DoctorImMsgListBean doctorImMsgListBean = oldDoctorImMsgList.get(i);
                    EMConversation conversation = EMClient.getInstance().chatManager().getConversation(doctorImMsgListBean.getPatientImAccount());
                    int unReadCount = 0;
                    if (conversation != null) {
                        unReadCount = conversation.getUnreadMsgCount();
                    }
                    oldDoctorImMsgList.get(i).setUnReadCount(unReadCount);
                    if (oldDoctorImMsgList.get(i).getImRecordHbaseDTO() != null) {
                        oldDoctorImMsgList.get(i).getImRecordHbaseDTO().setMsgType(msgType);
                        oldDoctorImMsgList.get(i).getImRecordHbaseDTO().setContent(content);
                        oldDoctorImMsgList.get(i).getImRecordHbaseDTO().setCustomEvent(event);
                        oldDoctorImMsgList.get(i).setUpdateTime(format);
                    } else {
                        OldConversationBean.DataBean.DoctorImMsgListBean.ImRecordHbaseDTOBean imRecordHbaseDTOBean = new OldConversationBean.DataBean.DoctorImMsgListBean.ImRecordHbaseDTOBean();
                        imRecordHbaseDTOBean.setMsgType(msgType);
                        imRecordHbaseDTOBean.setContent(content);
                        imRecordHbaseDTOBean.setCustomEvent(event);
                        oldDoctorImMsgList.get(i).setImRecordHbaseDTO(imRecordHbaseDTOBean);
                    }
                }
            }
        }
        refreshConversationList();
    }

    /**
     * 判断当前用户是否存在列表
     */
    boolean isExistMsgList(String from) {
        if (ConfigApi.Open.isOpenGroup){
            boolean isExist = false;
            for (int i = 0; i < doctorImMsgList.size(); i++) {
                if (doctorImMsgList.get(i).getPatientImAccount()!=null && doctorImMsgList.get(i).getPatientImAccount().equals(from)) {
                    isExist = true;
                    break;
                }
            }
            return isExist;
        }else{
            boolean isExist = false;
            for (int i = 0; i < oldDoctorImMsgList.size(); i++) {
                if (oldDoctorImMsgList.get(i).getPatientImAccount()!=null && oldDoctorImMsgList.get(i).getPatientImAccount().equals(from)) {
                    isExist = true;
                    break;
                }
            }
            return isExist;
        }
    }

    void refreshMsg(String from,boolean isCMD) {
        try {
            if (!isExistMsgList(from)) {
//                        doctorImMsgList.clear();
                getConversationList();
            } else {
                if (isCMD){
                    EMCursorResult<EMMessage> emMessageEMCursorResult = EMClient.getInstance().chatManager().fetchHistoryMessages(from, EMConversation.EMConversationType.Chat, 2, null);
                    if (emMessageEMCursorResult == null){
                        ALog.i(this.getClass().getName(),"emMessageEMCursorResult is null");
                    }else if (emMessageEMCursorResult.getData() == null){
                        ALog.i(this.getClass().getName(),"emMessageEMCursorResult.getData() is null");
                    }else if (emMessageEMCursorResult.getData().size() == 0){
                        ALog.i(this.getClass().getName(),"emMessageEMCursorResult.getData() size is 0");
                    }else{
                        EMMessage emMessage = emMessageEMCursorResult.getData().get(0);
                        emMessageJson(emMessage);
                    }
                }else{

                    EMCursorResult<EMMessage> emMessageEMCursorResult = EMClient.getInstance().chatManager().fetchHistoryMessages(from, EMConversation.EMConversationType.Chat, 1, null);
                    if (emMessageEMCursorResult == null){
                        ALog.i(this.getClass().getName(),"emMessageEMCursorResult is null");
                    }else if (emMessageEMCursorResult.getData() == null){
                        ALog.i(this.getClass().getName(),"emMessageEMCursorResult.getData() is null");
                    }else if (emMessageEMCursorResult.getData().size() == 0){
                        ALog.i(this.getClass().getName(),"emMessageEMCursorResult.getData() size is 0");
                    }else{
                        EMMessage emMessage = emMessageEMCursorResult.getData().get(0);
                        emMessageJson(emMessage);
                    }
                }

            }
        } catch (HyphenateException e) {
            e.printStackTrace();
        }
    }

    ///ihospital-doctor/ihospital/im/openImChargeByChargeListId
    void openImChargeByChargeListId(int chargesListId, int p){
        RequestParams params = new RequestParams();
        params.put("chargesListId",chargesListId);
        HttpUtils.get(UrlApi.openImChargeByChargeListId, params, new HttpCallBack<String>() {
            @Override
            public void onSuccess(String s, int i) {
                doctorImMsgList.get(p).setHaveRead(true);
                refreshConversationList();
            }

            @Override
            public void onFailure(String s, int i) {

            }
        });
    }
}
